<template>
  <div class="flex flex-col h-full">
    <!-- 联系人列表 -->
    <div class="flex-1 overflow-y-auto" v-loading="loading">

      <!-- 错误提示 -->
      <div v-if="error" class="flex flex-col items-center justify-center py-10 text-gray-500">
        <el-icon :size="48" class="mb-4">
          <Warning />
        </el-icon>
        <p>{{ error }}</p>
        <el-button type="primary" size="small" class="mt-4" @click="loadContacts">重试</el-button>
      </div>

      <template v-else>
        <!-- 索引列表 -->
        <div class="fixed right-1 flex flex-col items-center text-xs text-gray-400">
          <div v-for="letter in indexList" :key="letter" class="py-0.5 cursor-pointer hover:text-blue-500"
            @click="scrollToLetter(letter)">
            {{ letter }}
          </div>
        </div>

        <!-- 分组列表 -->
        <div v-for="(group, key) in groupedContacts" :key="key" class="mb-4"
          :ref="el => { if (el) letterRefs[key] = el as HTMLElement }">
          <!-- 分组标题 -->
          <div class="sticky top-0 px-4 py-2 text-xs font-medium text-gray-500 bg-gray-50/90 backdrop-blur-sm">
            {{ key }}
          </div>
          <!-- 分组内容 -->
          <div class="divide-y divide-gray-100">
            <div v-for="contact in group" :key="contact.id"
              class="flex items-center px-4 py-3 hover:bg-gray-50 cursor-pointer transition-colors"
              :class="{ 'bg-gray-50': selectedContact?.id === contact.id }" @click="handleContactClick(contact)">
              <el-avatar :size="40" :src="contact.avatar">
                {{ contact.nickname.charAt(0) }}
              </el-avatar>
              <div class="ml-3">
                <div class="text-m font-medium text-gray-900">{{ contact.remark || contact.username }}</div>
                <div class="text-xs text-gray-500">{{ contact.nickname }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 无联系人提示 -->
        <div v-if="Object.keys(groupedContacts).length === 0"
          class="flex flex-col items-center justify-center py-10 text-gray-500">
          <el-icon :size="48" class="mb-4">
            <User />
          </el-icon>
          <p>{{ contacts.length === 0 ? '暂无联系人' : '未找到相关联系人' }}</p>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { User, Warning } from '@element-plus/icons-vue'
import { pinyin } from 'pinyin-pro'
import { getFriendList } from '@/api/contact'
import type { FriendRequestData } from '@/types'

interface Props {
  filterQuery?: string
}

const props = withDefaults(defineProps<Props>(), {
  filterQuery: ''
})

const router = useRouter()
const selectedContact = ref<FriendRequestData | null>(null)
const letterRefs = ref<{ [key: string]: HTMLElement }>({})
const contacts = ref<FriendRequestData[]>([])
const loading = ref(false)
const error = ref<string | null>(null)

// 加载联系人数据
const loadContacts = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await getFriendList()
    contacts.value = response.data
  } catch (err: any) {
    error.value = err.message || '加载联系人失败'
  } finally {
    loading.value = false
  }
}

// 获取姓氏拼音首字母
const getSurnameInitial = (name: string) => {
  // 获取姓氏的拼音首字母
  const surname = name.charAt(0)
  const pinyinResult = pinyin(surname, { pattern: 'first', toneType: 'none' })
  return pinyinResult.toUpperCase()
}

// 按首字母分组
const groupedContacts = computed(() => {
  const filtered = contacts.value.filter(contact =>
    contact.nickname.toLowerCase().includes(props.filterQuery.toLowerCase()) ||
    contact.username.toLowerCase().includes(props.filterQuery.toLowerCase())
  )

  const grouped = filtered.reduce((groups: { [key: string]: FriendRequestData[] }, contact) => {
    const initial = getSurnameInitial(contact.nickname)
    if (!groups[initial]) {
      groups[initial] = []
    }
    groups[initial].push(contact)
    return groups
  }, {})

  // 对每个分组内的联系人按昵称排序
  Object.keys(grouped).forEach(key => {
    grouped[key].sort((a, b) => a.nickname.localeCompare(b.nickname, 'zh-CN'))
  })

  // 按字母顺序排序
  return Object.keys(grouped)
    .sort()
    .reduce((obj: { [key: string]: FriendRequestData[] }, key) => {
      obj[key] = grouped[key]
      return obj
    }, {})
})

// 索引列表
const indexList = computed(() => Object.keys(groupedContacts.value))

// 滚动到指定字母分组
const scrollToLetter = (letter: string) => {
  const element = letterRefs.value[letter]
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 处理联系人点击
const handleContactClick = (contact: FriendRequestData) => {
  selectedContact.value = contact
  router.push({
    name: 'contact-detail',
    params: { id: contact.id }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadContacts()
})
</script>

<style scoped>
/* 自定义滚动条样式 */
.overflow-y-auto {
  scrollbar-width: thin;
  scrollbar-color: #E5E7EB transparent;
}

.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: #E5E7EB;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background-color: #D1D5DB;
}
</style>